import 'package:common/common.dart';
import 'package:get/get.dart';
import 'package:miaowu/app/common/window_pop/public_btn_tem.dart';

import 'setting_state.dart';

/// @description:
/// @author
/// @date: 2025-01-21 14:28:41
class SettingLogic extends GetxController {
  final state = SettingState();

  @override
  void onReady() {
    super.onReady();
    calculateCacheSize();
    fetchgSystemSetConfig();
  }

  void fetchgSystemSetConfig() {
    HttpProvider.get('/user/getSystemSet', explain: '系统设置页', success: (result) {
      if (result.data["data"] is List) {
        state.list = result.data["data"] == null
            ? []
            : (result.data["data"] as List).map((e) => PublicBtnItem.fromJson(e)).toList();
      }
      logs(state.list);
      List<PublicBtnItem> array = [];
      for (PublicBtnItem element in state.list ?? []) {
        if (element.key != "logoutOpt") {
          array.add(element);
        }
        if (element.key == "blacksetJump") {
          array.add(PublicBtnItem());
        }
        if (element.key == "versionJump") {
          array.add(PublicBtnItem());
        }
        if (element.key == "logoutOpt") {
          state.logoutOpt = element;
        }
      }
      state.list = array;
      update();
    });
  }

  /// 退出登录的弹窗
  Future<void> showLogoutDialog() async {
    SmartDialog.show(
      usePenetrate: false,
      keepSingle: true,
      builder: (context) => CustomAlertWidget(
        title: "温馨提示",
        content: "你确定要退出登录吗？".tr,
        confirmAction: () {
          // 调用接口退出登录
          _userLogout();
        },
      ),
    );
  }

  /// 调用接口退出登录
  void _userLogout() async {
    // Toast.showLoading();
    // Result result = await HttpProvider.get('/client/logout', explain: '注销登录');
    // if (result.succ == true) {
    //   UserService.to.logout();
    //   AppMainPage.startWithPopAll();
    //   Toast.dismiss();
    // }
  }

  //计算当前 App 的 Cache 缓存
  void calculateCacheSize() async {
    final size = await AppCache.getAppCacheSize();
    state.appSize = AppCache.formatBytes(size);
    update();
  }

  //清除缓存
  void clearCache() async {
    SmartDialog.show(
      usePenetrate: false,
      builder: (context) => CustomAlertWidget(
        title: "温馨提示",
        content: "你确定你要清除应用缓存吗？".tr,
        confirmAction: () async {
          await AppCache.clearAppCache();
          state.appSize = '0 B';
          update();
        },
      ),
    );
  }
}
